const http = require('http')
const ms = require('mysql')
const port = 8000
const space = {
    users: [],
    loginUsers: []
}
const pool = ms.createPool({
    host: '127.0.0.1',
    port: '3306',
    user: 'root',
    password: 'qwer1234'
})
const query = function (sql, callback) {
    pool.getConnection(function (err, connection) {
        connection.query(sql, function (err, results) {
            callback(err, results)
            connection.release()
        })
    })
}
const server = http.createServer((req, res) => {
    switch (req.url) {
        case '/':
            query('select * from wuzi.user', (err, re) => {
                space.users = [...re]
                res.end(Response('同步人员成功!'))
            })
            break;
        case '/api/user':
            res.end(Response(space.users))
            break;
        case '/api/score':
            break;
        default:
            res.end(Response('请访问正确的接口'))
            break;
    }
})
server.listen(port)
console.log('启动成功! 监听端口：', port);

/**
 * @description 该方法用于格式化响应数据
 * @param {*} data：参数为响应的内容，可以为任意数据类型
 * @return {*} 
 */
function Response(data) {
    return JSON.stringify({
        code: 0,
        data,
        msg: 'success'
    })
}